/*
 * Copyright (C) 2005 Johan Maasing johan at zoom.nu Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package nu.zoom.swing.desktop.plugin.portunis.impl;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.swing.JFileChooser;

import nu.zoom.swing.ExtensionFilter;
import nu.zoom.swing.desktop.Workbench;
import nu.zoom.swing.desktop.common.BackendException;
import nu.zoom.swing.desktop.common.action.WorkbenchMessageAction;
import nu.zoom.swing.desktop.plugin.portunis.ApplicationPreferences;
import nu.zoom.swing.desktop.plugin.portunis.ZoomKeyStore;

import org.ops4j.gaderian.Messages;

/**
 * An action to impoert a certificate into a keystore.
 * 
 * @version $Revision: 1.1 $
 * @author $Author: johan $
 */
public class ImportCertificateAction extends WorkbenchMessageAction {

    private static final long serialVersionUID = -1;
    private final Workbench workbench;
    private final ZoomKeyStore store;
    private final ApplicationPreferences prefs;

    public ImportCertificateAction(final ApplicationPreferences prefs,
            final Workbench workbench, final Messages messages, final ZoomKeyStore store) {
        super(messages);
        this.workbench = workbench;
        this.store = store;
        this.prefs = prefs;
        setToolTipFromMessages("keystore.import.cert.tooltip");
        setIconFromMessages("keystore.import.cert.icon");
        setNameFromMessages("keystore.import.cert");
        setMnemonicKey(KeyEvent.VK_I);
        setAcceleratorKey(KeyEvent.VK_I, KeyEvent.CTRL_DOWN_MASK);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        final ExtensionFilter certFilter = new ExtensionFilter();
        certFilter.addExtension(".crt");
        certFilter.setDescription(messages.getMessage("keystore.import.cert.filetype"));
        final JFileChooser chooser = new JFileChooser();
        try {
            String startDir = prefs.getFileChooserStartDirectory();
            chooser.setCurrentDirectory(new File(startDir));
        } catch (BackendException e1) {
            // Don't set start directory
        }
        chooser.setFileFilter(certFilter);
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setToolTipText(messages.getMessage("keystore.import.cert.tooltip"));
        chooser.setDialogTitle(messages.getMessage("keystore.import.cert"));
        int option = chooser.showOpenDialog(workbench.getDialogOwner());
        if (option == JFileChooser.APPROVE_OPTION) {
            File certFile = chooser.getSelectedFile();
            if (certFile != null) {
                try {
                    InputStream certStream = new BufferedInputStream(
                            new FileInputStream(certFile));
                    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                    Certificate cert = certFactory.generateCertificate(certStream);
                    ImportCertificateDialog confirmDlg = new ImportCertificateDialog(
                            workbench, messages, cert, store);
                    Point location = workbench.getDialogOwner().getLocation() ;
                    location.x += 16 ;
                    location.y += 16 ;
                    confirmDlg.setLocation(location);
                    confirmDlg.pack();
                    if (confirmDlg.getHeight() > workbench.getDialogOwner().getHeight()) {
                        confirmDlg.setSize(
                                confirmDlg.getWidth(),
                                workbench.getDialogOwner().getHeight()-16);
                    }
                    confirmDlg.setVisible(true);
                    if (confirmDlg.isCloseOK()) {
                        store.setCertificateEntry(confirmDlg.getAlias(), cert);
                    }
                } catch (KeyStoreException exc) {
                    // Can not set the entry
                    workbench.getErrorReporter().reportError(
                            messages.getMessage("keystore.import.cert.error"),
                            exc);
                } catch (CertificateException exc) {
                    // Can not check if alias exists
                    workbench.getErrorReporter().reportError(
                            messages.getMessage("keystore.import.cert.error"),
                            exc);
                } catch (FileNotFoundException exc) {
                    workbench.getErrorReporter().reportError(
                            messages.getMessage("keystore.import.cert.error"),
                            exc);
                }
            }
        }
    }
}
